#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>

char key_val;
void *key_func ()
{
	key_val  = getchar ();
	return NULL;
}

int main (int argc, char ** argv)
{
	int fd = 0;
	pthread_t pt_key;
	unsigned char data = 0;
	int nbytes = 0;
	float val = 0;

	if (argc < 3) {
		printf ("usage: ./app_pcf8591 /dev/pcf8591 <channel>\n");
		printf ("<channel>: 0 1 3\n");
		printf ("  0: brightness\n");
		printf ("  1: tempeature\n");
		printf ("  3: volatge\n");
	}

	fd = open (argv[1], O_RDWR);
	if (fd < 0) {
		perror ("app open error!\n");
		return -1;
	}
	//创建一个线程函数接受用户输入
	pthread_create (&pt_key, NULL, key_func, NULL);
	printf ("press 'q' to exit...\n");
	usleep (1000000);
	
	//polling
	while (1) {
		data = (unsigned char)atoi (argv[2]);
		nbytes = read (fd, &data, 1);
		nbytes = write (fd, &data, 1);
		
		val = (float)data * (3.3/255);
		printf ("ADC%d = %.3fV\r\n", atoi(argv[2]), val);
		usleep (200000);
		if (key_val == 'q') {
			break;
		}
	}
	close (fd);
	system ("rmmod i2c_pcf8591");
	//线程的汇合 pthread_detach ---> 线程的分离  pthread_self 
	pthread_join (pt_key, NULL);
	return 0;
}
